﻿/*
Eventslistings methods
*/
function eventsListings(langID, id) {
};

eventsListings.init = function () {
    g_cityAnchors = $('.eventscity > ul').find('a');
//    $('.eventsdate dl dt a').click(function () {
//        //$('.eventsdate ol').slideToggle('slow');
//        $('#calendar').slideToggle('slow');
//    });

    $('.eventsdate dl dt a').click(function () {
        //$('.eventsdate ol').slideToggle('slow');
        $('#calendar').slideToggle('slow');
    });
    $('.eventsdate ol li a').click(function () {
        //$('.eventsdate ol').css('display','none');
        $('#calendar').css('display', 'none');
    });

    $('.eventscity dl dt a').attr('href', 'javascript:eventsListings.fitlerEventsByCity(0);');
    $('.eventstype dl dt a').attr('href', 'javascript:eventsListings.filterEventsByArtForm(0);');
    eventsListings.renderCities();
};

$().ready(function () {
    eventsListings.init();
});


////////////////////////////////////////////////////////////
var g_artForms = ArtForm.getArtForms(g_langID);
var g_cities = null;
var g_dates = null;
var g_selectedCityID = 0;       // 当前选中城市
var g_selectedArtFormID = 0;    // 当前选中艺术形式
var g_selectedYearMonth = 0;    // 当前选中年月
var g_selectedDate = 0;         // 当前选中日期
var g_currentPageIndex = 0;     // 当前分页代码
var g_artFormAnchors = null;
var g_cityAnchors = null;

eventsListings.renderCities = function () {
    // bind city id to city name href
    g_cities = getCityModels();
    bindCityID();
    eventsListings.fitlerEventsByCity(210); // 生成之后默认选中北京

    function getCityModels() {
        var url = "/GateService/EventGate.aspx?lang=" + g_langID + "&op=getCityModels&ram=" + new Date().toLocaleString();
        var req = new ajaxRequest(url);
        req.async = false;
        var models = null;
        req.get(function (res) {
            models = res;
        });

        return models;
    };
    
    

    function findCityIDByName(name) {
        var cities = g_cities;
        var cityID = null;
        var length = cities.length;
        for (var i = 0; i < length; i++) {
            var cityName = (g_langID == 2052) ? cities[i].Cnname : cities[i].Enname;
            if (cityName.toLowerCase() ==name.trim().toLowerCase()) {
                cityID = cities[i].Cid;
                break;
            }
        }
        return cityID;
    };

    String.prototype.trim = function () {
        var str = this,
        str = str.replace(/^\s\s*/, ''),
        ws = /\s/,
        i = str.length;
        while (ws.test(str.charAt(--i)));
            return str.slice(0, i + 1);
    }


    function bindCityID() {
        var liCities = $('.eventscity > ul').find('li');
        liCities.each(function () {
            //alert($(this).text());
            var cityID = findCityIDByName($(this).text());
            if (cityID != null) {
                $(this).find('a')
                    .attr('id', 'city_' + cityID)
                    .attr('cityID', cityID)
                    .click(function () { eventsListings.fitlerEventsByCity(cityID); });
            }
        });
    };
}

eventsListings.findCityNameByID = function (id) {
    var cities = g_cities;
    var cityName = null;
    var length = cities.length;
    for (var i = 0; i < length; i++) {
        if (cities[i].Cid == id) {
            cityName = (g_langID == 2052) ? cities[i].Cnname : cities[i].Enname;
            break;
        }
    }

    return cityName;
};

// 生成艺术形式
eventsListings.renderArtForms = function (selectedCityID) {
    // 根据城市获取在该城市举办的活动艺术形式
    selectedCityID = 0; // 原先客户要求根据城市对艺术形式进行筛选，现在又改主意了，所以这里不按照城市对艺术形式做过滤
    var artForms = getArtFormsByCityID(selectedCityID);

    var ulArtForms = $('.eventstype > ul').html('');
    var length = artForms.length;

    for (var i = 0; i < length; i++) {
        ulArtForms.append(createArtFormItem(artForms[i]));
    }

    g_artFormAnchors = $('.eventstype > ul').find('a');
    eventsListings.filterEventsByArtForm(0); // 生成之后默认选中全部

    function createArtFormItem(artForm) {
        // 生成形如 <li class="full"><a href="#" class="now"><span>全部</span></a></li> 的html
        var artFormID = (artForm == null) ? "0" : artForm.ID;
        var artFormName = (artForm == null) ? "" : artForm.Name;
        var id = 'artFormID_' + artFormID;
        var a = $('<a></a>').attr('id', id).attr('class', 'now').attr('href', 'javascript:eventsListings.filterEventsByArtForm(' + artFormID + ');').text(artFormName);

        var className = (artForm == null) ? "" : artForm.Css;
        var li = $('<li class="' + className + '"></li>').append(a);
        return li;
    }

    // 根据城市ID获取在该城市举办的活动的所有艺术形式
    function getArtFormsByCityID(cityID) {
        var url = Events.gateUrl + "?lang=" + g_langID + "&op=GetAllPublishedEventsArtForms&city=" + cityID + "&ram=" + new Date().toLocaleString();
        var req = new ajaxRequest(url);
        req.async = false;
        var artForms = null;
        req.get(function (res) {
            artForms = res;
        });
        return artForms;
    }
}

eventsListings.renderYearMonth = function (artFormID) {
    var selectedCityID = g_selectedCityID;
    var selectedArtFormID = artFormID;

    var allYearMonth = null;
    var url = Events.gateUrl + "?lang=" + g_langID + "&op=GetAllPublishedEventsYearMonth&city=" + selectedCityID + "&artForm=" + selectedArtFormID + "&ram=" + new Date().toLocaleString();
    var req = new ajaxRequest(url);
    req.async = false;
    req.get(function (list) {
        $('#calendar').html('').append(createYearMonthItem("0", eventsConstants.all));
       // $('.eventsdate > ol').html('').append(createYearMonthItem("0", eventsConstants.all));
        var length = list.length;
        allYearMonth = list;
        for (var i = 0; i < length; i++) {
            //$('.eventsdate > ol').append(createYearMonthItem(list[i], eventsListings.formatYearMonth(list[i])));
            $('#calendar').append(createYearMonthItem(list[i], eventsListings.formatYearMonth(list[i])));
        }
    });

//    $('.eventsdate ol li a').click(function () {
//        $('.eventsdate ol').css('display', 'none');
//    });
    $('#calendar li a').click(function () {
        $('#calendar').css('display', 'none');
    });

    g_selectedYearMonth = '0';
    eventsListings.filterEventsByYearMonth('0'); // 生成之后默认选中全部

    function createYearMonthItem(value, text) {
        var li = $('<li></li>');
        var a = $('<a></a>').attr("href", "javascript:eventsListings.filterEventsByYearMonth('" + value + "');").html(text);
        //var a = $('<a></a>').html(text);
        return li.append(a);
    };
}

eventsListings.renderDates = function (cityID, artFormID, yearMonth) {
    var ulWeek = $('.eventsdate > ul').html('');
    if (yearMonth != "0") {
        var maxDate = getMaxDate(yearMonth); // 获取当月最大天数
        var dates = getEventsDate(cityID, artFormID, yearMonth); // 获取当月有活动的日期
        g_dates = dates;
        for (var i = 1; i <= maxDate; i++) {
            var li = $('<li></li>');
            var a = $("<a></a>");
            var id = 'date_' + i;
            a.attr('id', id).attr('clicked', 'false').attr('href', 'javascript:eventsListings.filterEventsByDate("' + i + '");');
            if (eventsListings.hasEvents(dates, i))
                a.attr('class', 'have');
            a.html(i);
            li.append(a);
            ulWeek.append(li);
        }
    }
    eventsListings.filterEventsByDate(0);

    function getMaxDate(yearMonth) {
        if (yearMonth != '0') {
            var m = yearMonth.substr(5);
            if (m.substring(0, 1) == '0')
                m = m.substr(1);

            var d = new Date(parseInt(yearMonth.substring(0, 4)), parseInt(m), 0);
            return d.getDate();
        }

        return 0;
    }

    function getEventsDate(cityID, artFormID, yearMonth) {
        var url = Events.gateUrl + "?lang=" + g_langID + "&op=GetAllPublishedEventsDate&city=" + cityID + "&artForm=" + artFormID + "&yearMonth=" + yearMonth + "&ram=" + new Date().toLocaleString();
        var req = new ajaxRequest(url);
        req.async = false;
        var dates = null;
        req.get(function (res) {
            dates = res;
        });
        return dates;
    }
};

eventsListings.hasEvents = function (dates, date) {
    var length = dates.length;
    while (length > 0) {
        if (dates[length - 1] == date) return true;
        length--;
    }
    return false;
}

eventsListings.fitlerEventsByCity = function (cityID /*city_210*/) {
    g_currentPageIndex = 0;
    g_selectedCityID = cityID;

    var anchorID = "city_" + cityID;
    var clickedAnchor = $('#' + anchorID);
    if (cityID == 0)
        g_cityAnchors.attr('class', 'now');
    else {
        g_cityAnchors.attr('class', '');
        clickedAnchor.attr('class', 'now');
    }

    eventsListings.renderArtForms(g_selectedCityID);
}

eventsListings.filterEventsByArtForm = function (artFormID) {
    g_selectedArtFormID = artFormID;
    g_currentPageIndex = 0;               	// 页码清零

    var anchorID = "artFormID_" + artFormID;
    if (artFormID == 0) {
        g_artFormAnchors.attr('class', 'now');
    }
    else {
        g_artFormAnchors.attr('class', '');

        var clickedArtFormAnchor = $('#' + anchorID);
        clickedArtFormAnchor.attr('class', 'now');
    }

    eventsListings.renderYearMonth(artFormID);
}

eventsListings.filterEventsByYearMonth = function (yearMonth /*2012-02*/) {
    g_selectedYearMonth = yearMonth;
    g_currentPageIndex = 0;

    var cityID = g_selectedCityID;
    var artFormID = g_selectedArtFormID;

    $('.eventsdate dl').find('a').html((yearMonth == "0") ? eventsConstants.all : eventsListings.formatYearMonth(yearMonth));

    eventsListings.renderDates(cityID, artFormID, yearMonth); //首先生成月份对应的日期
};

eventsListings.formatYearMonth = function (yearMonth /**/) {
    if (g_langID == 1033)
        return eventsListings.formatEnYearMonth(yearMonth);
    else
        return yearMonth;
};

eventsListings.formatEnYearMonth = function (yearMonth /*2012-02*/) {
    if (yearMonth == null || typeof yearMonth == "undefined") return "";
    if (yearMonth.length < 7) return "ALL";
    var year = yearMonth.substring(0, 4);
    var sm = yearMonth.substr(5);
    if (sm.substring(0, 1) == "0") sm = sm.substr(1);
    var month = parseInt(sm);
    var dispMonth = getEnMonth(month, 'full');
    return dispMonth + " " + year;

    function getEnMonth(month, type) {
        var dispMonth = "";
        switch (month) {
            case 1:
                dispMonth = "January";
                break;
            case 2:
                dispMonth = "Feburary";
                break;
            case 3:
                dispMonth = "March";
                break;
            case 4:
                dispMonth = "April";
                break;
            case 5:
                dispMonth = "May";
                break;
            case 6:
                dispMonth = "June";
                break;
            case 7:
                dispMonth = "July";
                break;
            case 8:
                dispMonth = "August";
                break;
            case 9:
                dispMonth = "September";
                break;
            case 10:
                dispMonth = "October";
                break;
            case 11:
                dispMonth = "November";
                break;
            case 12:
                dispMonth = "December";
                break;
        }

        return (type == 'full') ? dispMonth : dispMonth.substring(0, 3);
    }
};

eventsListings.filterEventsByDate = function (date) {
    g_selectedDate = date;
    g_currentPageIndex = 0;

    var now = $('.eventsdate ul li').find('a.now');
    if (now != null && typeof now != 'undefined') {
        var nowID = now.attr('id');
        var has = false;
        if (nowID != null && typeof nowID != 'undefined') {
            has = eventsListings.hasEvents(g_dates, parseInt(nowID.substr(5)));
        }
        if (has)
            now.attr('class', 'have');
        else
            now.attr('class', '');
    }

    $('#date_' + date).attr('class', 'now');
    eventsListings.renderEvents(date);
};

eventsListings.renderEvents = function (selectedDate) {
    var cityID = g_selectedCityID;
    var artFormID = g_selectedArtFormID;
    var yearMonth = g_selectedYearMonth;
    var currPageIndex = g_currentPageIndex;
    // 处理Selection显示

    var txt = '<img src="/en/images/title_sub_selection.gif" alt="Selection">&nbsp;&nbsp;';
    if (cityID > 0) txt += eventsListings.findCityNameByID(cityID) + "&nbsp;&nbsp;";
    if (artFormID > 0) txt += ArtForm.getArtForm(g_langID, artFormID).Name + "&nbsp;&nbsp;";
    if (yearMonth != '0') {
        if (selectedDate > 0)
            txt += yearMonth + '-' + selectedDate;
        else
            txt += yearMonth;
    }
    $('.subtitle address').html(txt);

    $('#eventslist').html('');
    var pagingList = getFilteredEvents(cityID, artFormID, yearMonth, selectedDate, currPageIndex);
    var length = pagingList.List.length;
    for (var i = 0; i < length; i++) {
        var evt = pagingList.List[i];
        evt.LanguageID = g_langID;
        $('#eventslist').append(Events.getRenderHtml(evt));
    }

    renderPager(pagingList.Capacity, 0);      // 生成pager
    renderPager(pagingList.Capacity, 1);      // 生成pager

    function getFilteredEvents(cityID, artFormID, yearMonth, date, currPageIndex) {
        var url = Events.gateUrl + "?lang=" + g_langID + "&op=GetFilteredEventsModels&city=" + cityID + "&artForm=" + artFormID + "&yearMonth=" + yearMonth + "&date=" + date + "&currPageIndex=" + currPageIndex + "&ram=" + new Date().toLocaleString();
        var req = new ajaxRequest(url);
        req.async = false;
        var pagingList = null;
        req.get(function (res) {
            pagingList = res;
        });
        return pagingList;
    }
};

function renderPager(totalCount, num) {
	var ulPager = $('.subtitle:eq(' + num + ') ul'); 
    ulPager.html('');
	
	var pageSize = 12;
    var pageCount = Math.floor(totalCount / pageSize);
    if (totalCount % pageSize > 0) pageCount++;

    if (pageCount <= 1) return;

    //上一页
    var aPrev = $('<a></a>').html(eventsConstants.prev).attr('href', "javascript:jumpPage('p'," + pageCount + ");");
    var liPrev = $('<li></li>').append(aPrev);

    //页码
    var pageNum = (totalCount == 0) ? 0 : g_currentPageIndex + 1;
    var span = $('<span></span>').html(pageNum + '/' + pageCount);
    var liPage = $('<li></li>').append(span);

    //下一页
    var aNext = $('<a></a>').html(eventsConstants.next).attr('href', "javascript:jumpPage('n'," + pageCount + ");");
    var liNext = $('<li></li>').append(aNext);

    var spanGoto = $('<span></span>').html(eventsConstants.go);
    var liGoto = $('<li></li>').append(spanGoto);

    var txtGo = $('<abbr><input id="txtPage_' + num + '" type="text"/></abbr>');
    var liTxtGo = $('<li></li>').append(txtGo);

    var btnGo = $("<input name='' type='button' value='' />");
    btnGo.click(function () { goPage(pageCount, num); });
    var liBtn = $('<li></li>').append(btnGo);

    ulPager.append(liPrev).append(liPage).append(liNext).append(liGoto).append(liTxtGo).append(liBtn);
}

function validateInt(str, msg) {
    if (/^[1-9]+[0-9]*]*$/.test(str)) {
        return true;
    } else {
        alert(msg);
        return false;
    }
}

function retrieveAlterMessage(pageCount)
{
	if (g_langID == 2052)
		return '请输入 1 - ' + pageCount + ' 之间的整数！';
	else
		return 'Please input page number between 1 and ' + pageCount;
};

function goPage(pageCount, num) {
	var page = $('#txtPage_' + num).val();
	var msg = retrieveAlterMessage(pageCount);
    if (validateInt(page, msg)) {
        if (parseInt(page) > pageCount) {
            alert(msg);
            return;
        }
        g_currentPageIndex = parseInt(page) - 1;
        eventsListings.renderEvents(g_selectedDate);
    }
}

function jumpPage(dir, pageCount) {
    switch (dir) {
        case "f":
            g_currentPageIndex = 0;
            break;
        case "p":
            g_currentPageIndex--;
            break;
        case "n":
            g_currentPageIndex++;
            break;
        case "l":
            g_currentPageIndex = pageCount - 1;
            break;
    }

    if (g_currentPageIndex < 0) g_currentPageIndex = 0;
    if (g_currentPageIndex >= pageCount) g_currentPageIndex = pageCount - 1;

    eventsListings.renderEvents(g_selectedDate);
}